package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description: 链表实现
 * @author: 陈恩涛
 * @create: 2021-04-23 15:17
 **/
public class GeneralizedLinkedQueue<Item> implements Iterable<Item> {

    private class Node {
        private Item item;
        private Node next;
    }

    private Node first;
    private Node last;
    private int n;

    public boolean isEmpty() {
        return first == null;
    }

    public void insert(Item item) {
        Node insertNode = new Node();
        insertNode.item = item;
        if (isEmpty()) {
            first = last = insertNode;
        } else {
            last.next = insertNode;
            last = insertNode;
        }
        n++;
    }

    public Item delete(int k) {
        if (k > n || k <= 0) {
            throw new RuntimeException("Index is out the bounds!");
        }
        Node temp = first;
        Item result;
        if (k == 1) {
            result = first.item;
            first = first.next;
            if (isEmpty()) {
                last = first;
            }
            return result;
        }
        while (k > 2) {
            temp = temp.next;
            k--;
        }
        result = temp.next.item;
        if (temp.next == last) {
            temp.next = null;
            last = temp;
        } else {
            temp.next = temp.next.next;
        }
        n--;
        return result;
    }

    @Override
    public Iterator<Item> iterator() {
        return new GLQIterator(first);
    }

    class GLQIterator implements Iterator<Item> {

        private Node head;

        public GLQIterator(Node head) {
            this.head = head;
        }

        @Override
        public boolean hasNext() {
            return head != null;
        }

        @Override
        public Item next() {
            Item result = head.item;
            head = head.next;
            return result;
        }

        @Override
        public void remove() {

        }
    }

    public static void main(String[] args) {
        GeneralizedLinkedQueue<Integer> queue = new GeneralizedLinkedQueue<>();
        queue.insert(1);
        queue.insert(2);
        queue.insert(3);
        for (Integer i : queue) {
            System.out.println(i);
        }

        System.out.println("------------");
        System.out.println(queue.delete(3));
    }

}
